// 俄罗斯方块游戏类
class TetrisGame {
    constructor() {
        this.canvas = document.getElementById('tetris-canvas');
        this.ctx = this.canvas.getContext('2d');
        this.nextCanvas = document.getElementById('next-canvas');
        this.nextCtx = this.nextCanvas.getContext('2d');
        
        this.BLOCK_SIZE = 30;
        this.BOARD_WIDTH = 10;
        this.BOARD_HEIGHT = 20;
        
        this.board = [];
        this.currentPiece = null;
        this.nextPiece = null;
        this.score = 0;
        this.level = 1;
        this.lines = 0;
        this.dropTime = 0;
        this.dropInterval = 1000;
        this.isGameRunning = false;
        this.isPaused = false;
        
        this.initBoard();
        this.bindEvents();
        this.loadAndDisplayGameData();
    }

    // 初始化游戏板
    initBoard() {
        this.board = Array(this.BOARD_HEIGHT).fill().map(() => Array(this.BOARD_WIDTH).fill(0));
    }

    // 方块形状定义
    pieces = [
        // I 形状
        [
            [1, 1, 1, 1]
        ],
        // O 形状
        [
            [1, 1],
            [1, 1]
        ],
        // T 形状
        [
            [0, 1, 0],
            [1, 1, 1]
        ],
        // S 形状
        [
            [0, 1, 1],
            [1, 1, 0]
        ],
        // Z 形状
        [
            [1, 1, 0],
            [0, 1, 1]
        ],
        // J 形状
        [
            [1, 0, 0],
            [1, 1, 1]
        ],
        // L 形状
        [
            [0, 0, 1],
            [1, 1, 1]
        ]
    ];

    // 方块颜色
    colors = [
        '#FF0000', // 红色
        '#00FF00', // 绿色
        '#0000FF', // 蓝色
        '#FFFF00', // 黄色
        '#FF00FF', // 紫色
        '#00FFFF', // 青色
        '#FFA500'  // 橙色
    ];

    // 创建新方块
    createPiece() {
        const typeId = Math.floor(Math.random() * this.pieces.length);
        return {
            shape: this.pieces[typeId],
            color: this.colors[typeId],
            x: Math.floor(this.BOARD_WIDTH / 2) - Math.floor(this.pieces[typeId][0].length / 2),
            y: 0
        };
    }

    // 开始游戏
    async startGame() {
        this.initBoard();
        this.score = 0;
        this.level = 1;
        this.lines = 0;
        this.dropInterval = 1000;
        this.currentPiece = this.createPiece();
        this.nextPiece = this.createPiece();
        this.isGameRunning = true;
        this.isPaused = false;
        this.updateScore();
        await this.updateGameStats();
        this.gameLoop();
    }

    // 暂停/继续游戏
    togglePause() {
        if (this.isGameRunning) {
            this.isPaused = !this.isPaused;
            if (!this.isPaused) {
                this.gameLoop();
            }
        }
    }

    // 游戏主循环
    gameLoop() {
        if (!this.isGameRunning || this.isPaused) return;

        const now = Date.now();
        if (now - this.dropTime > this.dropInterval) {
            this.movePiece(0, 1);
            this.dropTime = now;
        }

        this.draw();
        requestAnimationFrame(() => this.gameLoop());
    }

    // 移动方块
    movePiece(dx, dy) {
        if (!this.currentPiece) return false;

        const newX = this.currentPiece.x + dx;
        const newY = this.currentPiece.y + dy;

        if (this.isValidPosition(this.currentPiece.shape, newX, newY)) {
            this.currentPiece.x = newX;
            this.currentPiece.y = newY;
            return true;
        } else if (dy > 0) {
            // 方块无法继续下降，固定到游戏板上
            this.placePiece();
            this.clearLines();
            this.currentPiece = this.nextPiece;
            this.nextPiece = this.createPiece();
            
            // 检查游戏结束
            if (!this.isValidPosition(this.currentPiece.shape, this.currentPiece.x, this.currentPiece.y)) {
                this.gameOver();
            }
        }
        return false;
    }

    // 旋转方块
    rotatePiece() {
        if (!this.currentPiece) return;

        const rotated = this.rotateMatrix(this.currentPiece.shape);
        if (this.isValidPosition(rotated, this.currentPiece.x, this.currentPiece.y)) {
            this.currentPiece.shape = rotated;
        }
    }

    // 旋转矩阵
    rotateMatrix(matrix) {
        const rows = matrix.length;
        const cols = matrix[0].length;
        const rotated = Array(cols).fill().map(() => Array(rows).fill(0));
        
        for (let i = 0; i < rows; i++) {
            for (let j = 0; j < cols; j++) {
                rotated[j][rows - 1 - i] = matrix[i][j];
            }
        }
        return rotated;
    }

    // 检查位置是否有效
    isValidPosition(shape, x, y) {
        for (let i = 0; i < shape.length; i++) {
            for (let j = 0; j < shape[i].length; j++) {
                if (shape[i][j]) {
                    const newX = x + j;
                    const newY = y + i;
                    
                    if (newX < 0 || newX >= this.BOARD_WIDTH || 
                        newY >= this.BOARD_HEIGHT || 
                        (newY >= 0 && this.board[newY][newX])) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    // 将方块放置到游戏板上
    placePiece() {
        for (let i = 0; i < this.currentPiece.shape.length; i++) {
            for (let j = 0; j < this.currentPiece.shape[i].length; j++) {
                if (this.currentPiece.shape[i][j]) {
                    const x = this.currentPiece.x + j;
                    const y = this.currentPiece.y + i;
                    if (y >= 0) {
                        this.board[y][x] = this.currentPiece.color;
                    }
                }
            }
        }
    }

    // 清除完整的行
    async clearLines() {
        let linesCleared = 0;
        
        for (let i = this.BOARD_HEIGHT - 1; i >= 0; i--) {
            if (this.board[i].every(cell => cell !== 0)) {
                this.board.splice(i, 1);
                this.board.unshift(Array(this.BOARD_WIDTH).fill(0));
                linesCleared++;
                i++; // 重新检查当前行
            }
        }
        
        if (linesCleared > 0) {
            this.lines += linesCleared;
            this.score += linesCleared * 100 * this.level;
            this.level = Math.floor(this.lines / 10) + 1;
            this.dropInterval = Math.max(100, 1000 - (this.level - 1) * 100);
            this.updateScore();
            await this.updateGameStats();
            await this.saveGameData();
        }
    }

    // 游戏结束
    async gameOver() {
        this.isGameRunning = false;
        await this.saveGameData();
        const data = await this.loadGameData();
        alert(`游戏结束！\n得分: ${this.score}\n等级: ${this.level}\n消除行数: ${this.lines}\n最高分: ${data.highScore}`);
    }

    // 更新分数显示
    updateScore() {
        document.getElementById('score').textContent = this.score;
    }

    // 绘制游戏
    draw() {
        // 清空画布
        this.ctx.fillStyle = '#000';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

        // 绘制游戏板
        for (let i = 0; i < this.BOARD_HEIGHT; i++) {
            for (let j = 0; j < this.BOARD_WIDTH; j++) {
                if (this.board[i][j]) {
                    this.ctx.fillStyle = this.board[i][j];
                    this.ctx.fillRect(j * this.BLOCK_SIZE, i * this.BLOCK_SIZE, 
                                    this.BLOCK_SIZE - 1, this.BLOCK_SIZE - 1);
                }
            }
        }

        // 绘制当前方块
        if (this.currentPiece) {
            this.ctx.fillStyle = this.currentPiece.color;
            for (let i = 0; i < this.currentPiece.shape.length; i++) {
                for (let j = 0; j < this.currentPiece.shape[i].length; j++) {
                    if (this.currentPiece.shape[i][j]) {
                        const x = (this.currentPiece.x + j) * this.BLOCK_SIZE;
                        const y = (this.currentPiece.y + i) * this.BLOCK_SIZE;
                        this.ctx.fillRect(x, y, this.BLOCK_SIZE - 1, this.BLOCK_SIZE - 1);
                    }
                }
            }
        }

        // 绘制下一个方块
        this.drawNextPiece();
    }

    // 绘制下一个方块
    drawNextPiece() {
        this.nextCtx.fillStyle = '#000';
        this.nextCtx.fillRect(0, 0, this.nextCanvas.width, this.nextCanvas.height);

        if (this.nextPiece) {
            this.nextCtx.fillStyle = this.nextPiece.color;
            const blockSize = 15;
            const offsetX = (this.nextCanvas.width - this.nextPiece.shape[0].length * blockSize) / 2;
            const offsetY = (this.nextCanvas.height - this.nextPiece.shape.length * blockSize) / 2;

            for (let i = 0; i < this.nextPiece.shape.length; i++) {
                for (let j = 0; j < this.nextPiece.shape[i].length; j++) {
                    if (this.nextPiece.shape[i][j]) {
                        this.nextCtx.fillRect(
                            offsetX + j * blockSize,
                            offsetY + i * blockSize,
                            blockSize - 1,
                            blockSize - 1
                        );
                    }
                }
            }
        }
    }

    // 绑定事件
    bindEvents() {
        document.addEventListener('keydown', (e) => {
            if (!this.isGameRunning || this.isPaused) return;

            switch (e.key) {
                case 'ArrowLeft':
                    this.movePiece(-1, 0);
                    break;
                case 'ArrowRight':
                    this.movePiece(1, 0);
                    break;
                case 'ArrowDown':
                    this.movePiece(0, 1);
                    break;
                case 'ArrowUp':
                    this.rotatePiece();
                    break;
                case ' ':
                    e.preventDefault();
                    this.togglePause();
                    break;
            }
        });
    }

    // 保存游戏数据
    async saveGameData() {
        const currentData = await this.loadGameData();
        const gameData = {
            highScore: Math.max(this.score, currentData.highScore || 0),
            lastScore: this.score,
            level: this.level,
            lines: this.lines
        };
        await authManager.saveGameData('tetris', gameData);
    }

    // 加载游戏数据
    async loadGameData() {
        return await authManager.loadGameData('tetris') || { highScore: 0 };
    }

    // 更新游戏统计显示
    async updateGameStats() {
        const data = await this.loadGameData();
        document.getElementById('level').textContent = this.level;
        document.getElementById('lines').textContent = this.lines;
        document.getElementById('high-score').textContent = data.highScore || 0;
    }

    // 加载并显示游戏数据
    async loadAndDisplayGameData() {
        await this.updateGameStats();
    }
}

// 创建游戏实例
let tetrisGame;